<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <el-col :span="24">
        <el-button type="primary">添加角色</el-button>
      </el-col>
    </el-row>
    <!-- row-key="id"
    如果这是一个嵌套的数据，rowkey 必须添加的属性-->
    <el-table :data="roleList" border>
      <!--打开展开列 -->
      <el-table-column type="expand">
        <!-- 填入咱们具体的这个角色所拥有的一级权限 -->
        <template slot-scope="scope">
          <el-row
            :key="item1.id"
            :class="['bdbottom',i1===0?'bdtop':'']"
            v-for="(item1,i1) in scope.row.children"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级三级权限 -->
            <el-col :span="19">
              <!-- 通过for循环来渲染二级权限 -->
              <el-row
                :class="[i2===0?'':'bdtop']"
                v-for="(item2,i2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    closable
                    @close="removeRightById(scope.row,item3.id)"
                    type="warning"
                    v-for="(item3) in item2.children"
                    :key="item3.id"
                  >{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-setting"
            @click="showSetRightDialog(scope.row)"
          >分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配权限得dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形菜单得内容 -->
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      rightsList: [],
      setRightDialogVisible: false,
      treeProps: {
        /**
         * 通过label设置树形节点文本展示什么:
         */
        label: 'authName',
        /**
         * 设置通过children属性展示子节点得信息
         */
        children: 'children'
      },
      /**
       * 设置一下树形控件中默认选中得内容
       */
      defkeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    async removeRightById(role, rightid) {
      /**
       * 弹窗表示用户是否要删除
       */
      const confirmResult = await this.$confirm('请问是否要删除这个权限', '删除提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      /**
       * confirm-- 点击确定   cancel  点击取消
       */
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
      /**
       * 这一块不需要全部更新，不需要重新加载全部得权限，只需要对现有得角色权限进行更新
       */
      role.children = res.data
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      /**
       * 点击分配权限按钮，展示对应得对话框
       */
      this.setRightDialogVisible = true
      /**
       * 获取所有权限得数据
       */
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限树失败')
      }
      this.rightsList = res.data
      /**
       * 写一个方法，来将咱们三级得权限添加到数组;
       */
      this.getLeftkeys(role, this.defkeys)
    },
    getLeftkeys(node, arr) {
      /**
       * 获取当前角色所有得三级权限得id添加到defkeys里面
       * 如果说当前节点不包含children属性，说明node是三级权限
       */
      if (!node.children) {
        return arr.push(node.id)
      }
      /**
       * 递归调用
       */
      node.children.forEach(item => {
        this.getLeftkeys(item, arr)
      })
    },
    async allotRights() {
      /**
       * 如果在树形对话框点击确定,将用户进行选择得，对权限进行更新;
       */
      /**
       * 先进性获取，选中得以及处于半选状态得内容
       */
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)
      /**
       * 将数组转化成字符串
       */
      const idStr = keys.join(',')
      /**
       * 发送请求来进行更新
       */
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      /**
       * 重新更新一下rolelist
       */
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  },
  /**
   * 关闭弹窗得时候
   */
  setRightDialogClose() {
    this.defkeys = []
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #ccc;
}
.bdbottom {
  border-bottom: 1px solid #ccc;
}
</style>
